package cn.changeforyou.analyzer.dbParse.mybatisPlusGenerator;

import cn.changeforyou.cmd.generator.CmdGenerator;
import cn.changeforyou.cmd.generator.CmdGeneratorParameter;
import cn.changeforyou.cmd.generator.GeneratorContext;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.generator.config.ConstVal;
import com.baomidou.mybatisplus.generator.config.builder.ConfigBuilder;
import com.baomidou.mybatisplus.generator.engine.AbstractTemplateEngine;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
import freemarker.template.Configuration;
import freemarker.template.Template;

import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.util.Map;


public class JavaparserTemplateEngine extends AbstractTemplateEngine implements CmdGenerator {
	
	private Configuration configuration;
	
	@Override
	public void writer(Map<String, Object> objectMap, String templatePath, String outputFile) throws Exception {
		Template template = configuration.getTemplate(templatePath);
		try (FileOutputStream fileOutputStream = new FileOutputStream(outputFile)) {
			
			ByteArrayOutputStream os = new ByteArrayOutputStream();
			template.process(objectMap, new OutputStreamWriter(os, ConstVal.UTF8));
			String newCode = new String(os.toByteArray(), ConstVal.UTF8);
			System.out.println(newCode);
		}
		logger.debug("模板:" + templatePath + ";  文件:" + outputFile);
	}
	
	@Override
	public String templateFilePath(String filePath) {
		return filePath + ".ftl";
	}
	
	@Override
	public String getSign() {
		return "javaparserTemplateEngine";
	}
	
	@Override
	public boolean generate_do(GeneratorContext context, CmdGeneratorParameter params) {
		return false;
	}
	
	@Override
	public String getName() {
		return "javaparser模板引擎";
	}
	
	@Override
	public Class getParameterClass() {
		return null;
	}
	
	@Override
	public void init(GeneratorContext context) {
	
	}
	
	@Override
	public JavaparserTemplateEngine init(ConfigBuilder configBuilder) {
		super.init(configBuilder);
		configuration = new Configuration(Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS);
		configuration.setDefaultEncoding(ConstVal.UTF8);
		configuration.setClassForTemplateLoading(FreemarkerTemplateEngine.class, StringPool.SLASH);
		return this;
	}
}
